package main;
import tools.Help;
import tools.Log;
import tools.ProgramParameters;
import game.Game;
import graphics.main.MainRenderer;
import graphics.main.Window;
import network.RSocket;
import network.protocol.ClientHandler;
import network.protocol.ServerHandler;
import network.socket.TCPClient;
import network.socket.TCPServer;
public class Start {
	public static TCPServer s;
	public static TCPClient cs;
	public static void main(String[] args) {
		Config.load("config/config");
		// The parameters state whether this instance of rohXel is a server or a
		// client.
		boolean server = ProgramParameters.contains(args, "s");
		String mapname = getMapname(args);
		boolean debug = ProgramParameters.contains(args, "d");
		boolean noplayer = ProgramParameters.contains(args, "np");
		// creates a window
		Window win = new Window();
		win.setMaxfps(Config.MAXFPS);
		// Set the window title so we can see whether this one is a server or a
		// client.
		win.setTitle("Rohxel - " + (server ? "Server" : "Client"));
		// creates a renderer which must be attached to a window
		MainRenderer render = createRenderer(server, mapname, debug, noplayer);
		// attach renderer to window
		win.setRenderer(render);
		win.startMainloop();
		win.cleanUp();
		if (server) {
			s.close();
		}
		else {
			cs.close();
		}
	}
	private static String getMapname(String[] args) {
		String mapname = ProgramParameters.value(args, "map");
		if (mapname == "") {
			Log.game("No map name given -> selecting empty level as map");
		}
		return mapname;
	}
	private static MainRenderer createRenderer(boolean server, String mapname, boolean debug, boolean noplayer) {
		// the type of the renderer depends, when this instance of rohXel is a
		// server : just create a new game and we're done.
		// If its a client we need to get the initial game state from the
		// clientHandler, create a game from that and create the renderer
		// afterwards
		MainRenderer render;
		if (server) {
			render = new MainRenderer();// needs to be called first because of opengl-initialization
			render.simplerender = debug;
			s = new TCPServer(5432);
			// s.start();
			ServerHandler sh = new ServerHandler();
			sh.setServerSocket(s);
			Game g = new Game(sh, mapname);
			render.setGame(g);
			g.initialize();
			if (!noplayer)
				g.addPlayer(0);
		}
		else {
			render = new MainRenderer(); // needs to be called first because of
											// opengl-initialization
											// render.simplerender = debug;
			// s = new UDPClientSocket("192.168.0.40");
			cs = new TCPClient("localhost", 5432);
			// s.start();
			// ((UDPClientSocket) s).sayHello();
			ClientHandler c = new ClientHandler();
			c.setServer(cs);
			// Game g = c.initializeGame();
			// Set references
			// g.setNetworkHandler(c);
			// c.setGame(g);
			c.initialize();
			render.setGame(c.getGame());
		}
		return render;
	}
}
